﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StyleMVVM.DependencyInjection.Conditions
{
	public class WhenAppSettingNotPresentOrFalse : IExportCondition
	{
		private readonly string settingName;
		private readonly bool cacheAnswer;
		private bool? answer;

		public WhenAppSettingNotPresentOrFalse(string settingName, bool cacheAnswer)
		{
			this.settingName = settingName;
			this.cacheAnswer = cacheAnswer;
		}

		public bool ConditionMeet(IDependencyInjectionContainer container,
		                          IInjectionContext injectionContext,
		                          IExportStrategy exportStrategy)
		{
			if (answer.HasValue)
			{
				return answer.Value;
			}

			string appSetting = ConfigurationManager.AppSettings[settingName];
			bool returnValue = false;

			if (string.IsNullOrEmpty(appSetting) ||
			    string.Compare("false", appSetting, StringComparison.CurrentCultureIgnoreCase) == 0)
			{
				returnValue = true;
			}

			if (cacheAnswer)
			{
				answer = returnValue;
			}

			return returnValue;
		}
	}
}